package bi.uc.pay;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import com.bi_uc.www.R;

import bi.uc.client.ExitApplication;
import bi.uc.client.QuickpayActivity;
import bi.uc.client.ReadMemberInfoActivity;
import bi.uc.login.Info;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.util.Base64;
import android.util.Log;
import android.util.Xml;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

public class CardUserActivity extends Activity implements OnClickListener,
		OnTouchListener, OnFocusChangeListener, Runnable {
	EditText cardNum;
	Info info = Info.getInfo();
	TextView ownmoney;
	TextView ownscore;
	ImageButton searchCardNum;
	EditText needPay;
	TextView payMoney;
	TextView result;
	EditText money;
	EditText score;
	TextView scoreMoney;
	EditText cash;
	EditText password;
	double returnmoney;
	TextWatcher needPayWatcher;
	TextWatcher scoreWatcher;
	TextWatcher moneyWatcher;
	TextWatcher cashWatcher;
	
	TableRow ownmoneyrow;
	TableRow moneyrow;
	TableRow ownscorerow;
	TableRow scorerow;
	TableRow scoremoneyrow;
	TableRow passwordrow;
	TableRow cashrow;
	
	public HashMap<String, HashMap<String, String>> goodsInfo;
	public ArrayList<HashMap<String, String>> source;
	String json;
	String sellinfo;
	double sellByPrice = 0;
	double sellSum = 0;
	int scores = 0;
	double returnMoney = 0;
	double hasPayMoney = 0;
	double needmoney = 0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		setContentView(R.layout.carduseractivity);
		goodsInfo = (HashMap<String, HashMap<String, String>>) getIntent().getSerializableExtra("goodsInfo");
		source = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("source");	
		ownmoneyrow = (TableRow) findViewById(R.id.ownmoneyrow);
		moneyrow = (TableRow) findViewById(R.id.moneyrow);
		ownscorerow = (TableRow) findViewById(R.id.ownscorerow);
		scorerow = (TableRow) findViewById(R.id.scorerow);
		scoremoneyrow = (TableRow) findViewById(R.id.scoremoneyrow);
		passwordrow = (TableRow) findViewById(R.id.passwordrow);
		cashrow = (TableRow) findViewById(R.id.cashrow);
		cardNum = (EditText) findViewById(R.id.cardNum);
		ownmoney = (TextView) findViewById(R.id.ownmoney);
		ownscore = (TextView) findViewById(R.id.ownscore);
		needPay = (EditText) findViewById(R.id.needpay);
		payMoney = (TextView) findViewById(R.id.paymoney);
		result = (TextView) findViewById(R.id.result);
		money = (EditText) findViewById(R.id.money);
		score = (EditText) findViewById(R.id.score);
		scoreMoney = (TextView) findViewById(R.id.scoremoney);
		cash = (EditText) findViewById(R.id.cash);
		password = (EditText) findViewById(R.id.password);
		needPay.setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (info.isChangeNeedPay) {					
					needPay.setFocusableInTouchMode(true);
				} else {
					needPay.setFocusableInTouchMode(false);					
				}
				return false;
			}
		});
		initTextWatcher();
		if (!info.isCardPay) {
			ownmoneyrow.setVisibility(View.GONE);
			moneyrow.setVisibility(View.GONE);
			ownscorerow.setVisibility(View.GONE);
			scorerow.setVisibility(View.GONE);
			scoremoneyrow.setVisibility(View.GONE);
			passwordrow.setVisibility(View.GONE);
		} else {
			money.setOnFocusChangeListener(this);
			score.setOnFocusChangeListener(this);
			score.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					if (info.card.isScorePay ) {					
						score.setFocusableInTouchMode(true);
					} else {
						Toast.makeText(CardUserActivity.this, "该卡未启用积分抵现！", Toast.LENGTH_SHORT).show();
						score.setFocusableInTouchMode(false);
					}
					return false;
				}
			});
			password.setOnTouchListener(new OnTouchListener() {
				
				@Override
				public boolean onTouch(View v, MotionEvent event) {
					// TODO Auto-generated method stub
					if (info.isPayNeedPassword && (Math.abs(Double.parseDouble(money.getText().toString()))>0.0000001 || !score.getText().toString().equals("0"))) {					
						password.setFocusableInTouchMode(true);
					} else {
						password.setFocusableInTouchMode(false);
					}
					return false;
				}
			});
		}
		
		if (!info.isCashPay) {
			Log.d("****", "*****");
			cashrow.setVisibility(View.GONE);
		} else {
			cash.setOnFocusChangeListener(this);
		}
		if (info.isExist(info.card.cardNum)) {
			cardNum.setText(info.card.cardNum);
			ownmoney.setText(info.subZeroAndDot(info.card.money+"") + "元");
			ownscore.setText(info.card.score + "枚");
			
			needPay.setEnabled(true);			
			money.setEnabled(true);
			score.setEnabled(true);			
			cash.setEnabled(true);
			data();
			String needmoney = info.subZeroAndDot(Math.round(100*(sellByPrice+sellSum*info.storeDiscount*info.card.Discount))/100.0+"");
			needPay.setText(needmoney);
			adjustPayMoney(needmoney);
		}		
		searchCardNum = (ImageButton) findViewById(R.id.searchbtn);
		searchCardNum.setOnClickListener(this);
		searchCardNum.setOnTouchListener(this);
		needPay.setOnFocusChangeListener(this);		
	}

	/**
	 * 
	 */
	private void initTextWatcher() {
		// TODO Auto-generated method stub
		needPayWatcher = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start,
					int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start,
					int count, int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				Log.d("needpay", "结果：" + s.toString());
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0') {
					needPay.setText(s.toString().substring(1));
					info.setSpan(needPay);
					return;
				}
				if (".".equals(s.toString())) {
					needPay.setText("0.");
					info.setSpan(needPay);
					return;
				}
				if (s.length()>0) {
					adjustPayMoney(s.toString());
				} else {
						needPay.setText("0");
						info.setSpan(needPay);
						money.setText("0");
						scoreMoney.setText("0元");
						payMoney.setText("0元");
						result.setText("");
						returnmoney = 0;
						score.setText("0");
						cash.setText("0");
				}
			}
		};
		
		moneyWatcher = new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				Log.d("money", "结果：" + s.toString());
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0') {
					money.setText(s.toString().substring(1));
					info.setSpan(money);
					return;
				}
				if (s.length() < 1) {
					money.setText("0");
					info.setSpan(money);
					return;
				}
				if (".".equals(s.toString())) {
					money.setText("0.");
					info.setSpan(money);
					return;
				}
				double cardPayMoney = Double.parseDouble(s.toString());
				double needmoney = Double.parseDouble(needPay.getText().toString());
				if (cardPayMoney > info.card.money) {
					money.setText(info.subZeroAndDot(info.card.money+""));
					info.setSpan(money);
					return;
				}
				if (cardPayMoney > needmoney) {
					money.setText(info.subZeroAndDot(""+Math.round(needmoney*100)/100.0));
					info.setSpan(money);
					return;
				} else {
					
					// 需要继续支付的金额
					double shortMoney = needmoney-cardPayMoney;
					
					if (info.card.isScorePay && shortMoney > 0) {
						double scoreMaxMoney = info.card.score/info.card.scoreMoneyExchange;
						// 积分抵现的限额
						double canExchangeMoney = needmoney*info.card.scoreMoneyRatio;
						if (canExchangeMoney >= shortMoney
								&& scoreMaxMoney >= shortMoney) {
							score.setText(""+(int)(shortMoney/info.card.scoreMoneyExchange));
							cash.setText("0");
							shortMoney = 0;
						} else {
							if ((canExchangeMoney >= shortMoney && scoreMaxMoney < shortMoney)
									|| (canExchangeMoney < shortMoney && scoreMaxMoney <= canExchangeMoney)) {
								score.setText(""+ info.card.score);
							} else if (canExchangeMoney < shortMoney
									&& scoreMaxMoney > canExchangeMoney) {
								score.setText(""+(int)(canExchangeMoney
												/info.card.scoreMoneyExchange));
							}
//							cash.setText(String.format("%.2f",shortMoney-Integer.parseInt(score.getText().toString())/info.card.scoreMoneyExchange));
							shortMoney -= Integer.parseInt(score.getText().toString())/info.card.scoreMoneyExchange;
						}
						
						scoreMoney.setText(info.subZeroAndDot(Math.round(Integer.parseInt(score.getText().toString())*100/info.card.scoreMoneyExchange)/100.0+"")+"元");
					} else {
						score.setText("0");
						scoreMoney.setText("0元");
//						cash.setText(String.format("%.2f",shortMoney));
					}
//					result.setText("结清");
					shortMoney -= Double.parseDouble(cash.getText().toString());
					payMoney.setText(info.subZeroAndDot(Math.round(100*(needmoney-shortMoney))/100.0+"")+"元");
					if (shortMoney>0.0000001) {
						result.setText("少付"+info.subZeroAndDot(Math.round(100*shortMoney)/100.0+"")+"元");
						returnmoney = 0;
					} else if (Math.abs(shortMoney)<0.0000001) {
						result.setText("结清");
						returnmoney = 0;
					} else {
						result.setText("找零"+info.subZeroAndDot(Math.round(-100*shortMoney)/100.0+"")+"元");
						returnmoney = Math.round(-100*shortMoney)/100.0;
					}
				}
			}
		};
		
		scoreWatcher = new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0') {
					score.setText(s.toString().substring(1));
					info.setSpan(score);
					return;
				}
				if (s.length() < 1) {
					score.setText("0");
					info.setSpan(score);
					return;
				}

				double needmoney = Double.parseDouble(needPay.getText().toString());
				double cardPayMoney = Double.parseDouble(money.getText().toString());
				// 需要继续支付的金额
				double shortMoney = needmoney-cardPayMoney;
				if ("0".equals(s.toString())) {
					scoreMoney.setText("0元");
//					cash.setText(String.format("%.2f", shortMoney));
//					result.setText("结清");
					shortMoney -= Double.parseDouble(cash.getText().toString());
					if (shortMoney>0.0000001) {
						result.setText("少付"+info.subZeroAndDot(Math.round(100*shortMoney)/100.0+"")+"元");
						returnmoney = 0;
					} else if (Math.abs(shortMoney)<0.0000001) {
						result.setText("结清");
						returnmoney = 0;
					} else {
						result.setText("找零"+info.subZeroAndDot(Math.round(-100*shortMoney)/100.0+"")+"元");
						returnmoney = Math.round(-100*shortMoney)/100.0;
					}
					payMoney.setText(info.subZeroAndDot(Math.round(100*cardPayMoney)/100.0+"")+"元");
					return;
				}
								
				// 允许兑换的金额上限
				double scoreMaxMoney = info.card.score/info.card.scoreMoneyExchange;				
				// 积分抵现可以兑换的最大金额
				double canExchangeMoney = needmoney*info.card.scoreMoneyRatio;				
				double exchangeMoney = Integer.parseInt(s.toString())/info.card.scoreMoneyExchange;				
				if (shortMoney>=0) {
					if (exchangeMoney<=scoreMaxMoney && exchangeMoney<=canExchangeMoney && exchangeMoney <= shortMoney) {
//						cash.setText(String.format("%.2f", shortMoney-exchangeMoney));
						shortMoney -= exchangeMoney + Double.parseDouble(cash.getText().toString());
						
						scoreMoney.setText(info.subZeroAndDot(Math.round(100*exchangeMoney)/100.0+"")+"元");
//						result.setText("结清");
//						payMoney.setText(shortMoney+"元");
						payMoney.setText(info.subZeroAndDot(Math.round(100*(needmoney-shortMoney))/100.0+"")+"元");
						if (shortMoney>0.0000001) {
							result.setText("少付"+info.subZeroAndDot(Math.round(100*shortMoney)/100.0+"")+"元");
							returnmoney = 0;
						} else if (Math.abs(shortMoney)<0.0000001) {
							result.setText("结清");
							returnmoney = 0;
						} else {
							result.setText("找零"+info.subZeroAndDot(Math.round(-100*shortMoney)/100.0+"")+"元");
							returnmoney = Math.round(-100*shortMoney)/100.0;
						}
						return;
					} else if (exchangeMoney>scoreMaxMoney && exchangeMoney<=canExchangeMoney && exchangeMoney <= shortMoney) {
						score.setText(""+(int)(scoreMaxMoney/info.card.scoreMoneyExchange));
					} else if (exchangeMoney<=scoreMaxMoney && exchangeMoney>canExchangeMoney && exchangeMoney <= shortMoney) {
						score.setText(""+(int)(canExchangeMoney/info.card.scoreMoneyExchange));
					} else if (exchangeMoney<=scoreMaxMoney && exchangeMoney<=canExchangeMoney && exchangeMoney > shortMoney) {
						score.setText(""+(int)(shortMoney/info.card.scoreMoneyExchange));
					} else if (exchangeMoney<=scoreMaxMoney && exchangeMoney>canExchangeMoney && exchangeMoney > shortMoney) {
						if (canExchangeMoney < shortMoney) {
							score.setText(""+(int)(canExchangeMoney/info.card.scoreMoneyExchange));
						}else {
							score.setText(""+(int)(shortMoney/info.card.scoreMoneyExchange));
						}
					} else if (exchangeMoney>scoreMaxMoney && exchangeMoney>canExchangeMoney && exchangeMoney <= shortMoney) {
						if (scoreMaxMoney < canExchangeMoney) {
							score.setText(""+(int)(scoreMaxMoney/info.card.scoreMoneyExchange));
						}else {
							score.setText(""+(int)(canExchangeMoney/info.card.scoreMoneyExchange));
						}
					} else if (exchangeMoney>scoreMaxMoney && exchangeMoney<=canExchangeMoney && exchangeMoney > shortMoney) {
						if (scoreMaxMoney < shortMoney) {
							score.setText(""+(int)(scoreMaxMoney/info.card.scoreMoneyExchange));
						}else {
							score.setText(""+(int)(shortMoney/info.card.scoreMoneyExchange));
						}
					}
					info.setSpan(score);
				}
				
			}
		};
	
		cashWatcher = new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if (s.length() > 1 && s.charAt(1) != '.'
						&& s.charAt(0) == '0'){
					cash.setText(s.toString().substring(1));
					info.setSpan(cash);
					return;
				}
				if (s.length() < 1) {
					cash.setText("0");
					info.setSpan(cash);
					return;
				}
				if (".".equals(s.toString())) {
					cash.setText("0.");
					info.setSpan(cash);
					return;
				}
				double needmoney = Double.parseDouble(needPay.getText().toString());				
				double hasPayMoney = Double.parseDouble(s.toString())+Double.parseDouble(money.getText().toString())+(info.card.isScorePay?Integer.parseInt(score.getText().toString())/info.card.scoreMoneyExchange:0);
				double countResult = hasPayMoney - needmoney;
				payMoney.setText(info.subZeroAndDot(""+Math.round(100*hasPayMoney)/100.0)+"元");
				if (countResult>0.0000001) {
					result.setText("找零"+info.subZeroAndDot(Math.round(100*countResult)/100.0+"")+"元");
					returnmoney = Math.round(100*countResult)/100.0;
				} else if (Math.abs(countResult)<0.0000001) {
					returnmoney = 0;
					result.setText("结清");
				} else {
					returnmoney = 0;
					result.setText("少付"+info.subZeroAndDot(Math.round(-100*countResult)/100.0+"")+"元");
				}
			}
		};
	}

	/**
	 * 
	 */
	protected void adjustPayMoney(String s) {
		// TODO Auto-generated method stub
		if (!info.isCardQuickPay) {
			return;
		}
		double needmoney = Double.parseDouble(s);
		if (info.card.money < needmoney) {
			
			// 需要继续支付的金额
			double shortMoney = needmoney-info.card.money;			
			if (info.card.isScorePay && shortMoney > 0) {
				// 积分抵现的限额
				double canExchangeMoney = needmoney*info.card.scoreMoneyRatio;
				// 可以兑换的金额上限
				double scoreMaxMoney = info.card.score/info.card.scoreMoneyExchange;
				if (canExchangeMoney >= shortMoney
						&& scoreMaxMoney >= shortMoney) {
					score.setText(""+(int)(shortMoney/info.card.scoreMoneyExchange));
					cash.setText("0");
					shortMoney = 0;
				} else {
					if ((canExchangeMoney >= shortMoney && scoreMaxMoney < shortMoney)
							|| (canExchangeMoney < shortMoney && scoreMaxMoney <= canExchangeMoney)) {
						score.setText(""+info.card.score);
						
					} else if (canExchangeMoney < shortMoney
							&& scoreMaxMoney > canExchangeMoney) {
						score.setText(""+(int)(canExchangeMoney/info.card.scoreMoneyExchange));
					}
//					cash.setText(String.format("%.2f",shortMoney-Integer.parseInt(score.getText().toString())/info.card.scoreMoneyExchange));
					shortMoney -= Integer.parseInt(score.getText().toString())/info.card.scoreMoneyExchange;
				}
				double exchangeMoney = Math.round(100*Double.parseDouble(score.getText().toString())/info.card.scoreMoneyExchange)/100.0;
				scoreMoney.setText(info.subZeroAndDot(exchangeMoney+"")+"元");
			} else {
				score.setText("0");
				scoreMoney.setText("0元");
//				cash.setText(String.format("%.2f",shortMoney));
			}
			shortMoney -= Double.parseDouble(cash.getText().toString());
			money.setText(info.subZeroAndDot(""+info.card.money));
//			result.setText("结清");						
			payMoney.setText(info.subZeroAndDot(Math.round((needmoney-shortMoney)*100)/100.0+"")+"元");
			if (shortMoney>0.0000001) {
				result.setText("少付"+info.subZeroAndDot(Math.round(shortMoney*100)/100.0+"")+"元");
				returnmoney = 0;
			} else if (Math.abs(shortMoney)<0.0000001) {
				result.setText("结清");
				returnmoney = 0;
			} else {
				result.setText("找零"+info.subZeroAndDot(Math.round(-shortMoney*100)/100.0+"")+"元");
				returnmoney = Math.round(-shortMoney*100)/100.0;
			}
			
		}else {
			money.setText(s);
			result.setText("结清");
			returnmoney = 0;
			scoreMoney.setText("0元");
			payMoney.setText(s + "元");
			score.setText("0");
			cash.setText("0");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnTouchListener#onTouch(android.view.View,
	 * android.view.MotionEvent)
	 */
	@Override
	public boolean onTouch(View view, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.searchbtn:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				searchCardNum.setBackgroundColor(Color.TRANSPARENT);
			} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
				searchCardNum.setBackgroundColor(Color.rgb(51, 102, 153));
			}
			break;
		default:

			break;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.searchbtn:
			Intent intent = new Intent(this, ReadMemberInfoActivity.class);
			startActivityForResult(intent, 2);
			Toast.makeText(this, "读取卡号", Toast.LENGTH_SHORT).show();
			break;
		case R.id.btnOK:
			if (info.stopFlag) {
				Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
						.show();
			} else {
				if (!info.isExist(info.card.cardNum)) {
					Toast.makeText(this, "请先读取会员卡信息！", Toast.LENGTH_SHORT).show();
					return;
				}else if (goodsInfo.isEmpty()) {
					Toast.makeText(this, "清单中没有商品，请添加商品！", Toast.LENGTH_SHORT).show();
					return;
				
//				} else if ("0".equals(needPay.getText().toString())) {
//					Toast.makeText(this, "请输入应付金额", Toast.LENGTH_SHORT).show();
//					return;
				} else if (info.isPayNeedPassword && "".equals(password.getText().toString()) && (!"0".equals(info.subZeroAndDot(money.getText().toString())) || !"0".equals(score.getText().toString()))) {
					Toast.makeText(this, "请输入会员密码！", Toast.LENGTH_SHORT).show();					
					return;
				}
				new Thread(this).start();
			}
			break;
//		case R.id.password:
//			if (Math.abs(Double.parseDouble(money.getText().toString()))>0.0000001 || !score.getText().toString().equals("0")) {
//				password.setFocusable(true);
//				Log.d("1", "1111");
////				password.setEnabled(true);
//			} else {
//				password.setFocusable(false);
//				Log.d("1", "2222");
//			}
//			break;
		default:
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 2:
			if (resultCode == Activity.RESULT_OK) {
				cardNum.setText(info.card.cardNum);
				ownmoney.setText(info.subZeroAndDot(info.card.money+"") + "元");
				ownscore.setText(info.card.score + "枚");
				needPay.setEnabled(true);		
				money.setEnabled(true);
				score.setEnabled(true);			
				cash.setEnabled(true);
				password.setText("");
				data();
				String needmoney = info.subZeroAndDot(Math.round(100*(sellByPrice+sellSum*info.storeDiscount*info.card.Discount))/100.0+"");
				needPay.setText(needmoney);
				adjustPayMoney(needmoney);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 
	 */
	private void data() {
		// TODO Auto-generated method stub
		JSONArray jsonArray = new JSONArray();
		try {
			json = writeJSON(jsonArray);
			sellinfo = writeXml(jsonArray);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	private String writeJSON(JSONArray jsonArray) throws Exception{
		for (HashMap<String, String> value : source) {
			JSONObject jsonObject = new JSONObject(value);
			HashMap<String, String> map = goodsInfo.get(value.get("条码"));
			String goodsName = value.get("商品");
			jsonObject.put("pItem_Name", goodsName);
			jsonObject.put("pItem_Id", map.get("pItem_Id"));
			jsonObject.put("pItem_Barcode", value.get("条码"));
			jsonObject.put("pItem_SellingPrice", value.get("单价"));
			jsonObject.put("pItem_DiscountRate", map.get("pItem_DiscountRate"));
			jsonObject.put("pItem_IntegralRate", map.get("pItem_IntegralRate"));
			double discount = Double.parseDouble(map.get("pItem_DiscountRate"));
			double Integral = Double.parseDouble(map.get("pItem_IntegralRate"));
			String[] arr = getMemberRule(goodsName);
			jsonObject.put("储值消费明细_会员日折扣", arr[0]);
			jsonObject.put("储值消费明细_会员日积分", arr[1]);
			double money = Double.parseDouble(value.get("总价"));
			double paymoney;
			int integral;	//积分
			integral = (int)(money*Double.parseDouble(arr[0])*(info.isGoodsDiscount?Integral:1));
			scores += integral;
			if ("1".equals(map.get("pItem_IsSellByPrice"))) {
				paymoney = money;
				sellByPrice += paymoney;
			}else{
				paymoney = money*Double.parseDouble(arr[0])*(info.isGoodsDiscount?discount:1);
				sellSum += paymoney;
			}
			jsonObject.put("Payment", info.subZeroAndDot(paymoney+""));
			jsonObject.put("Integral", integral);
			jsonObject.put("Consume_Number", Integer.parseInt(value.get("数量")));
			jsonObject.put("pItem_IsSellByPrice", Integer.parseInt(map.get("pItem_IsSellByPrice")));
			jsonObject.put("is_leaf", true);
			jsonArray.put(jsonObject);
		}
		return Base64.encodeToString(jsonArray.toString().getBytes(),Base64.DEFAULT);
	}

	/**
	 * @param ruleArray
	 * @param length
	 * @throws JSONException
	 */
	private String[] getMemberRule(String goodsName)
			throws JSONException {
		String[] arr = new String[2];
		arr[0] = "1";
		arr[1] = "1";
		
		Time time = new Time();     
		time.setToNow(); 
		int year = time.year;    
		int month = time.month+1;    
		int day = time.monthDay;    
		int minute = time.minute;    
		int hour = time.hour;
		int weekday = time.weekDay;
		int sec = time.second;

      Log.d("Time","当前时间为：" + year +     
		                    "年 " + month +     
		                    "月 " + day +     
		                    "日 " + hour +     
		                    "时 " + minute +     
		                    "分 " + sec +     
		                    "秒");    
		JSONArray ruleArray = info.card.ruleArray; //获取会员日规则
		int length = ruleArray.length();
		for(int i = 0; i < length; i++){
			//遍历JSONArray  
			Log.d("json",Integer.toString(i));
			JSONObject js = ruleArray.getJSONObject(i).getJSONObject("source");
			Log.d("json","类型："+js.getString("类型"));
			if ("每年".equals(js.getString("类型"))) {
				Log.d("json","起始日期()："+js.getString("起始日期"));
				String start[] = js.getString("起始日期").split("-");
				Log.d("json","起始日期："+start[0]+"-"+start[1]);
				int s[] = {Integer.parseInt(start[0]), Integer.parseInt(start[1])};
				String end[] = js.getString("截止日期").split("-");
				int e[] = {Integer.parseInt(end[0]), Integer.parseInt(end[1])};
				if ((month>s[0]&&month<e[0]) || (month==s[0]&&day>=s[1]) ||
						(month==e[0]&&day<=e[1])) {
					Log.d("json","success!");
					JSONArray listArray = js.getJSONArray("时段");
					int size = listArray.length();
					for (int j = 0; j < size; j++) {
						JSONObject js1 = listArray.getJSONObject(j);
						start = js1.getString("开始时间").split(":");
						s[0] = Integer.parseInt(start[0]);
						s[1] = Integer.parseInt(start[1]);
						end = js1.getString("结束时间").split(":");
						e[0] = Integer.parseInt(end[0]);
						e[1] = Integer.parseInt(end[1]);
						int min = hour*60+minute;
						String name = js1.getString("商品名称");
						Log.d("会员日规则", "商品名称:"+name);
						if (("".equals(name)||goodsName.equals(name)) && min>=s[0]*60+s[1] && min<=e[0]*60+e[1]) {
							arr[0] = js1.getString("折扣系数");
							arr[1] = js1.getString("积分系数");
							Log.d("会员日规则", "折扣系数："+arr[0]+"积分系数:"+arr[1]);
							return arr;
						}
					}					
				}
			} else if ("每月".equals(js.getString("类型"))) {
				Log.d("json","起始日期()："+js.getString("起始日期"));
				String start = js.getString("起始日期");
			
				int s = Integer.parseInt(start);
				String end = js.getString("截止日期");
				int e = Integer.parseInt(end);
				if (day>=s && day<=e) {
					Log.d("json","success!");
					JSONArray listArray = js.getJSONArray("时段");
					int size = listArray.length();
					for (int j = 0; j < size; j++) {
						JSONObject js1 = listArray.getJSONObject(j);
						String[] arr1 = js1.getString("开始时间").split(":");
						int startArr[] = {Integer.parseInt(arr1[0]), Integer.parseInt(arr1[1])};					
						String[] arr2 = js1.getString("结束时间").split(":");
						int endArr[] = {Integer.parseInt(arr2[0]), Integer.parseInt(arr2[1])};		
						int min = hour*60+minute;
						String name = js1.getString("商品名称");
						Log.d("会员日规则", "商品名称:"+name);
						if (("".equals(name)||goodsName.equals(name)) && min>=startArr[0]*60+startArr[1] && min<=endArr[0]*60+endArr[1]) {
							arr[0] = js1.getString("折扣系数");
							arr[1] = js1.getString("积分系数");
							Log.d("会员日规则", "折扣系数："+arr[0]+"积分系数:"+arr[1]);
							return arr;
						}
					}					
				}
			} else if ("每周".equals(js.getString("类型"))) {
				JSONArray weeks= js.getJSONArray("周几");
				int size = weeks.length();
				for (int j = 0; j < size; j++) {
					if (weekday == weeks.getInt(j)) {
						JSONArray listArray = js.getJSONArray("时段");
						int len = listArray.length();
						for (int k = 0; k < len; k++) {
							JSONObject js1 = listArray.getJSONObject(k);
							String[] arr1 = js1.getString("开始时间").split(":");
							int startArr[] = {Integer.parseInt(arr1[0]), Integer.parseInt(arr1[1])};					
							String[] arr2 = js1.getString("结束时间").split(":");
							int endArr[] = {Integer.parseInt(arr2[0]), Integer.parseInt(arr2[1])};		
							int min = hour*60+minute;
							String name = js1.getString("商品名称");
							Log.d("会员日规则", "商品名称:"+name);
							if (("".equals(name)||goodsName.equals(name)) && min>=startArr[0]*60+startArr[1] && min<=endArr[0]*60+endArr[1]) {
								arr[0] = js1.getString("折扣系数");
								arr[1] = js1.getString("积分系数");
								Log.d("会员日规则", "折扣系数："+arr[0]+"积分系数:"+arr[1]);
								return arr;
							}
						}					
					}
				}
			} else if ("自定义".equals(js.getString("类型"))) {
				Log.d("json","起始日期()："+js.getString("起始日期"));
				String start[] = js.getString("起始日期").split("-");
				int s[] = {Integer.parseInt(start[0])*12+Integer.parseInt(start[1]), Integer.parseInt(start[2])};
				String end[] = js.getString("截止日期").split("-");
				int e[] = {Integer.parseInt(end[0])*12+Integer.parseInt(end[1]), Integer.parseInt(end[2])};
				int compareMonth = year*12+month;
				
				if ((compareMonth>s[0]&&compareMonth<e[0]) || (compareMonth==s[0]&&day>=s[1]) ||
						(compareMonth==e[0]&&day<=e[1])) {
					Log.d("json","success!");
					JSONArray listArray = js.getJSONArray("时段");
					int size = listArray.length();
					for (int j = 0; j < size; j++) {
						JSONObject js1 = listArray.getJSONObject(j);
						start = js1.getString("开始时间").split(":");
						s[0] = Integer.parseInt(start[0]);
						s[1] = Integer.parseInt(start[1]);
						end = js1.getString("结束时间").split(":");
						e[0] = Integer.parseInt(end[0]);
						e[1] = Integer.parseInt(end[1]);
						int min = hour*60+minute;
						String name = js1.getString("商品名称");
						Log.d("会员日规则", "商品名称:"+name);
						if (("".equals(name)||goodsName.equals(name)) && min>=s[0]*60+s[1] && min<=e[0]*60+e[1]) {
							arr[0] = js1.getString("折扣系数");
							arr[1] = js1.getString("积分系数");
							Log.d("会员日规则", "折扣系数："+arr[0]+"积分系数:"+arr[1]);
							return arr;
						}
					}					
				}
				
			}
		}
		return arr;
	}

	private String writeXml(JSONArray jsonArray) throws Exception {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		serializer.setOutput(writer);
		// <?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
//		serializer.startDocument("UTF-8", true);
		// <储值消费明细>
		serializer.startTag("", "储值消费明细");
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsob = jsonArray.getJSONObject(i);
			// <行记录 ...>
			serializer.startTag("", "行记录");
			serializer.attribute("", "储值消费明细_商品", jsob.getString("pItem_Id"));
			serializer.attribute("", "储值消费明细_商品名称",
					jsob.getString("pItem_Name"));
			serializer.attribute("", "储值消费明细_商品售价",
					jsob.getString("pItem_SellingPrice"));
			serializer.attribute("", "储值消费明细_折扣系数",
					jsob.getString("pItem_DiscountRate"));
			serializer.attribute("", "储值消费明细_积分系数",
					jsob.getString("pItem_IntegralRate"));
			serializer.attribute("", "储值消费明细_会员日折扣", 
					jsob.getString("储值消费明细_会员日折扣"));
			serializer.attribute("", "储值消费明细_会员日积分", 
					jsob.getString("储值消费明细_会员日积分"));
			serializer.attribute("", "储值消费明细_是否以原价销售",
					jsob.getString("pItem_IsSellByPrice"));
			serializer.attribute("", "储值消费明细_套餐", "0");
			serializer.attribute("", "储值消费明细_套餐名称", "");
			serializer.attribute("", "储值消费明细_备注", "");
			serializer.attribute("", "数量", jsob.getString("Consume_Number"));
			serializer.attribute("", "商品名称", jsob.getString("pItem_Name"));
			serializer
					.attribute("", "售价", jsob.getString("pItem_SellingPrice"));
			serializer
					.attribute("", "折扣", jsob.getString("pItem_DiscountRate"));
			serializer.attribute("", "金额", jsob.getString("Payment"));
			serializer.endTag("", "行记录");
		}
		serializer.startTag("", "提成人");
		serializer.endTag("", "提成人");
		serializer.endTag("", "储值消费明细");
		serializer.endDocument();
		Log.d("tag", "结果："+writer.toString());
		return Base64.encodeToString(writer.toString().getBytes(),
				Base64.DEFAULT);

	}	
		
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.view.View.OnFocusChangeListener#onFocusChange(android.view.View,
	 * boolean)
	 */
	@Override
	public void onFocusChange(View view, boolean hasFocus) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.needpay:
			if (hasFocus) {
				needPay.addTextChangedListener(needPayWatcher);
			} else {
				needPay.removeTextChangedListener(needPayWatcher);
			}
			break;

		case R.id.money:
			if (hasFocus) {
				money.addTextChangedListener(moneyWatcher);
			} else {
				money.removeTextChangedListener(moneyWatcher);
			}
			break;
		case R.id.score:
			if (hasFocus) {
				score.addTextChangedListener(scoreWatcher);
			} else {				
				score.removeTextChangedListener(scoreWatcher);
			}
			break;
		case R.id.cash:
			if (hasFocus) {
				cash.addTextChangedListener(cashWatcher);
			} else {
				cash.removeTextChangedListener(cashWatcher);
			}
			break;
		default:
			break;
		}
	}

	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			send();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 */
	private void send()  throws Exception{
		// TODO Auto-generated method stub
				String Url = "http://bi.bi-uc.com/BI.api";
				/*String Body = "Action=PDA-充值&商家=" + info.employID + "&店面="
						+ info.shopID + "&操作员=" + info.userID + "&卡号=" + cardNumString
						+ "&充值金额=" + moneyString;
				Log.d("data", Body);*/
				HttpPost httpRequest = new HttpPost(Url);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				NameValuePair pair1 = new BasicNameValuePair("Action", "PDA-储值消费");
				NameValuePair pair2 = new BasicNameValuePair("商家", info.employID);				
				NameValuePair pair3 = new BasicNameValuePair("卡号", info.card.cardNum);
				NameValuePair pair4 = new BasicNameValuePair("店面", info.shopID);
				NameValuePair pair5 = new BasicNameValuePair("找零金额", info.subZeroAndDot(returnmoney+""));
				NameValuePair pair6 = new BasicNameValuePair("应付金额", needPay.getText().toString());
				StringBuffer sb = new StringBuffer(payMoney.getText());
				NameValuePair pair7 = new BasicNameValuePair("实付金额", sb.deleteCharAt(sb.length()-1).toString());
				NameValuePair pair8 = new BasicNameValuePair("操作员", info.userID);
				NameValuePair pair9 = new BasicNameValuePair("储值支付", money.getText().toString());
				NameValuePair pair10 = new BasicNameValuePair("积分支付", score.getText().toString());
				sb = new StringBuffer(scoreMoney.getText());
//				Log.d("积分抵现", sb.deleteCharAt(sb.length()-1).toString());
				NameValuePair pair11 = new BasicNameValuePair("积分抵现", sb.deleteCharAt(sb.length()-1).toString());
				NameValuePair pair12 = new BasicNameValuePair("现金支付", cash.getText().toString());
				
				NameValuePair pair13 = new BasicNameValuePair("密码", password.getText().toString());
				String sellByDiscount = Math.round(100*sellSum*info.card.Discount*(info.isChangeNeedPay?info.storeDiscount:1))/100.0+"";
				NameValuePair pair14 = new BasicNameValuePair("支付总额", info.subZeroAndDot(sellByDiscount));
				NameValuePair pair15 = new BasicNameValuePair("支付总额原价出售", info.subZeroAndDot(Math.round(100*sellByPrice)/100.0+""));
				NameValuePair pair16 = new BasicNameValuePair("店面折扣", info.subZeroAndDot(""+info.storeDiscount));
				NameValuePair pair17 = new BasicNameValuePair("会员折扣", info.subZeroAndDot(""+info.card.Discount));
				NameValuePair pair18 = new BasicNameValuePair("店面积分系数", info.subZeroAndDot(""+info.storeFactor));
				NameValuePair pair19 = new BasicNameValuePair("会员积分系数", info.subZeroAndDot(""+info.card.Factor));
				NameValuePair pair20 = new BasicNameValuePair("消费获得积分", String.valueOf(scores));			
				NameValuePair pair21 = new BasicNameValuePair("获得积分", String.valueOf((int)(scores*info.storeFactor*info.card.Factor)));
				NameValuePair pair22 = new BasicNameValuePair("消费记录", json);
				NameValuePair pair23 = new BasicNameValuePair("储值消费明细", sellinfo);
				Log.d("data", "应付金额:"+needPay.getText().toString()+"实付金额:"+pair6.getValue()
						+"储值支付:"+pair8.getValue()+"积分支付:"+pair9.getValue()
						+"积分抵现:"+pair10.getValue()+"现金支付:"+pair11.getValue()+"密码:"+pair12.getValue());
				params.add(pair1);
				params.add(pair2);
				params.add(pair3);
				params.add(pair4);
				params.add(pair5);
				params.add(pair6);
				params.add(pair7);
				params.add(pair8);
				params.add(pair9);
				params.add(pair10);
				params.add(pair11);
				params.add(pair12);
				params.add(pair13);
				params.add(pair14);
				params.add(pair15);
				params.add(pair16);
				params.add(pair17);
				params.add(pair18);
				params.add(pair19);
				params.add(pair20);
				params.add(pair21);
				params.add(pair22);
				params.add(pair23);
				HttpEntity entity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				httpRequest.setEntity(entity);
				DefaultHttpClient client = new DefaultHttpClient();
				HttpResponse response = client.execute(httpRequest);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					/*InputStream in = response.getEntity().getContent();
					BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));  
					StringBuffer responseMessage = new StringBuffer();
					int charCount = -1;  
					   while ((charCount = br.read()) != -1) {  
						    responseMessage.append((char) charCount);  
						   }  
					   Log.d("tag", responseMessage.toString());*/
					
					InputStream in = response.getEntity().getContent();// 接收服务器的数据
					XmlPullParserFactory pullParserFactory = XmlPullParserFactory
							.newInstance();    // 获取XmlPullParser的实例					
					final XmlPullParser parser = pullParserFactory.newPullParser();
					InputStreamReader responseReader = new InputStreamReader(in,
							"UTF-8");
					parser.setInput(responseReader);
					parser.next();
					int eventType = parser.getEventType();
					if (eventType != XmlPullParser.END_DOCUMENT) {
						if (eventType == XmlPullParser.START_TAG
								&& parser.getName().equals("XML")) { // String result = parser.getAttributeValue(0);
							String result = parser.getAttributeValue(null, "EXEC");
							if (result.equals("True")) {
								info.card.money = info.card.money - Double.parseDouble(money.getText().toString());					
								info.card.score = info.card.score - Integer.parseInt(score.getText().toString());
								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Intent intent = getIntent();						 
										/* 将数据打包到aintent Bundle 的过程略 */
										setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
										finish();
									}
								});
								
							} else {
								
								final String error = parser.getAttributeValue(null, "错误消息");
								Log.e("data",error);
								if (error.contains("您的可用短信数量为")) {
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(CardUserActivity.this, error,
													Toast.LENGTH_SHORT).show();
											Intent intent = getIntent();						 
											/* 将数据打包到aintent Bundle 的过程略 */
											setResult(RESULT_OK, intent); //这理有2个参数(int resultCode, Intent intent)															 
											finish();
										}
										
									});
									
								} else {
									runOnUiThread(new Runnable() {

										@Override
										public void run() {
											// TODO Auto-generated method stub
											Toast.makeText(CardUserActivity.this, "会员储值消费失败！"+error,
													Toast.LENGTH_SHORT).show();
										}
									});
								}
								
								
							}
						}
					}
					in.close();
				
					responseReader.close();
				}
				else
				{
					runOnUiThread(new Runnable() {				
						@Override
						public void run() {
							Toast.makeText(CardUserActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
							}
					});	
				}		
	}
	
}
